<template>
  <div class="comment-section">
    <!-- 评论输入框 -->
    <div class="comment-input">
      <h3 style="font-weight: bold">所有评论：{{ totalCommentCount }}</h3>
      <!--      <a-avatar :src="currentUser?.userAvatar" />-->
      <a-textarea
        v-model:value="commentContent"
        :placeholder="replyUser ? `回复 @${replyUser.userName}：` : '发表你的评论...'"
        :auto-size="{ minRows: 6, maxRows: 8 }"
      />
      <div class="comment-actions">
        <a-button v-if="replyUser" @click="cancelReply">取消回复</a-button>
        <a-button type="primary" @click="submitComment" :loading="submitting">发布</a-button>
      </div>
    </div>

    <!-- 评论列表 -->
    <div class="comment-list">
      <a-list
        v-if="rootComments.length > 0"
        :data-source="rootComments"
        :pagination="pagination"
        gutter="10"
        item-layout="horizontal"
      >
        <template #renderItem="{ item }">
          <a-list-item>
            <a-comment
              :author="item.userName"
              :avatar="item.userAvatar"
              :content="item.content"
              :datetime="formatDate(item?.createTime)"
            >
              <template #actions>
                <span @click="handleReply(item)">回复</span>
                <span @click="item.hasLiked ? handleUnlike(item) : handleLike(item)">
                  <like-outlined v-if="item.hasLiked" style="color: #1890ff" />
                  <like-outlined v-else />
                  {{ item.likeCount > 0 ? item.likeCount : '点赞' }}
                </span>
                <span v-if="canDelete(item)" @click="handleDelete(item)">删除</span>
              </template>

              <!-- 子评论区域 -->
              <div v-if="item.childCount > 0" class="reply-list" :class="{ active: isShow }">
                <div
                  v-if="!item.children || item.children.length === 0 || !isShow"
                  class="load-more"
                >
                  <span class="clickable-text" @click="loadReplies(item.id)"
                    >查看{{ item.childCount }}条回复</span
                  >
                  <DownOutlined />
                </div>
                <a-list v-else-if="isShow" :data-source="item.children" item-layout="horizontal">
                  <template #renderItem="{ item: reply }">
                    <a-list-item>
                      <a-comment
                        :author="reply.userName"
                        :avatar="reply.userAvatar"
                        :content="getReplyContent(reply)"
                        :datetime="formatDate(reply?.createTime)"
                      >
                        <template #actions>
                          <span @click="handleReply(reply, item)">回复</span>
                          <span @click="reply.hasLiked ? handleUnlike(reply) : handleLike(reply)">
                            <like-outlined v-if="reply.hasLiked" style="color: #1890ff" />
                            <like-outlined v-else />
                            {{ reply.likeCount > 0 ? reply.likeCount : '点赞' }}
                          </span>
                          <span v-if="canDelete(reply)" @click="handleDelete(reply)">删除</span>
                        </template>
                      </a-comment>
                    </a-list-item>
                  </template>
                </a-list>
                <div v-if="hasMoreReplies(item)" class="load-more">
                  <a @click="loadMoreReplies(item.id)">加载更多回复</a>
                </div>
                <div class="isShow" v-else-if="isShow">
                  <span class="clickable-text" @click="holdReplyList(item.id)">收起</span>
                  <UpOutlined />
                </div>
              </div>
            </a-comment>
          </a-list-item>
        </template>
      </a-list>
      <a-empty v-else description="暂无评论，快来发表第一条评论吧！" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import { LikeOutlined } from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import dayjs from 'dayjs'
// 引入API命名空间
import '@/api/typings.d.ts'
import {
  addCommentUsingPost,
  deleteCommentUsingPost,
  replyCommentVoByPageUsingPost,
  rootCommentVoByPageUsingPost,
} from '@/api/commentController'

import { DownOutlined, UpOutlined } from '@ant-design/icons-vue'

const props = defineProps({
  postId: {
    type: Number,
    required: true,
  },
})

// 定义emit
const emit = defineEmits(['comment-added', 'comment-deleted'])

// 用户信息
const userStore = useLoginUserStore()
const loginUser = userStore.loginUser
const currentUser = computed(() => loginUser)

// 评论状态
const commentContent = ref('')
const rootComments = ref<API.CommentVO[]>([])
const submitting = ref(false)
const replyUser = ref<API.CommentVO | null>(null)
const replyRootComment = ref<API.CommentVO | null>(null)
const isShow = ref(false)

// 分页配置
const pagination = reactive({
  onChange: (page: number) => {
    searchParams.current = page
    loadRootComments()
  },
  pageSize: 10,
  total: 0,
  current: 1,
})

// 查询参数
const searchParams = reactive<API.CommentQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'descend',
  postId: props.postId, // 添加文章ID
})

const searchReplyParams = reactive<API.CommentQueryRequest>({
  current: 1,
  pageSize: 5,
  sortField: 'createTime',
  sortOrder: 'ascend',
  postId: undefined, // 将在加载回复时设置为rootId
})

// 回复页码记录
const replyPages = reactive<Record<string, number>>({})

onMounted(() => {
  loadRootComments()
})

// 格式化日期
const formatDate = (date: string | Date) => {
  if (!date) return ''
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 计算总评论数
const totalCommentCount = computed(() => {
  let total = 0
  // 计算所有评论和它们的嵌套回复
  rootComments.value.forEach((comment) => {
    // 计算每个根评论（1个）加上它的所有嵌套回复
    total += 1 + (comment.childCount || 0)
  })
  return total
})

// 判断是否需要显示"加载更多回复"按钮
const hasMoreReplies = (comment: API.CommentVO): boolean => {
  if (!comment.children || comment.children.length === 0) {
    return false
  }

  // 通过比较已加载的回复和实际子评论数来判断
  console.log(comment.children.length,"------", comment.childCount)
  return comment.childCount !== undefined && comment.children.length < comment.childCount
}

// 收起子评论列表，并清空子评论数据
const holdReplyList = (commentId: number) => {
  const rootComment = rootComments.value.find((item) => item.id === commentId)
  if (rootComment) {
    rootComment.children = []
    if (rootComment.id) {
      replyPages[rootComment.id] = 1
    }
  }
  isShow.value = false
}

// 加载一级评论
const loadRootComments = async () => {
  try {
    searchParams.postId = props.postId // 确保每次都使用最新的postId
    const response = await rootCommentVoByPageUsingPost(searchParams)

    if (response.data && response.data.code === 0) {
      rootComments.value = response.data.data?.records || []
      pagination.total = response.data.data?.total || 0
      pagination.current = response.data.data?.current || 1

      // 初始化子评论页码
      rootComments.value.forEach((comment) => {
        if (comment.id && !replyPages[comment.id]) {
          replyPages[comment.id] = 1
        }
      })
    } else {
      rootComments.value = []
    }
  } catch (error) {
    message.error('加载评论失败')
    console.error(error)
  }
}

// 加载二级评论
const loadReplies = async (rootCommentId: number) => {
  if (!rootCommentId) return

  try {
    console.log("===============",rootCommentId, "---", replyPages[rootCommentId])
    searchReplyParams.current = replyPages[rootCommentId] || 1
    searchReplyParams.postId = rootCommentId // 设置为根评论ID作为查询参数

    console.log('Loading replies for comment ID:', rootCommentId, 'with params:', searchReplyParams)
    const response = await replyCommentVoByPageUsingPost(searchReplyParams)

    console.log('Reply response:', response.data)
    if (response.data && response.data.code === 0 && response.data.data) {
      // 找到对应的根评论并更新其子评论
      const rootComment = rootComments.value.find((item) => item.id === rootCommentId)
      if (rootComment) {
        console.log(
          'Found root comment:',
          rootComment.id,
          'Setting children:',
          response.data.data.records
        )
        rootComment.children = response.data.data.records || []
      }
    }
    isShow.value = true
  } catch (error) {
    message.error('加载回复失败')
    console.error(error)
  }
}

// 加载更多回复
const loadMoreReplies = async (rootCommentId: number) => {
  if (!rootCommentId) return

  try {
    const currentPage = replyPages[rootCommentId] || 1
    const nextPage = currentPage + 1

    searchReplyParams.current = nextPage
    searchReplyParams.postId = rootCommentId

    const response = await replyCommentVoByPageUsingPost(searchReplyParams)

    if (response.data && response.data.code === 0 && response.data.data) {
      // 找到对应的根评论
      const rootComment = rootComments.value.find((item) => item.id === rootCommentId)
      if (rootComment) {
        // 合并新加载的回复
        rootComment.children = [
          ...(rootComment.children || []),
          ...(response.data.data.records || []),
        ]
        // 更新页码
        replyPages[rootCommentId] = nextPage
      }
    }
  } catch (error) {
    message.error('加载更多回复失败')
    console.error(error)
  }
}

// 提交评论
const submitComment = async () => {
  if (!currentUser.value) {
    message.warning('请先登录')
    return
  }

  if (!commentContent.value.trim()) {
    message.warning('评论内容不能为空')
    return
  }

  submitting.value = true

  try {
    const params = reactive<API.CommentAddRequest>({
      content: commentContent.value,
      postId: props.postId,
    })

    // 如果是回复评论
    if (replyUser.value) {
      params.parentId = replyUser.value.id
      params.replyUserId = replyUser.value.userId

      // 设置根评论ID
      if (replyRootComment.value) {
        params.rootId = replyRootComment.value.id
      } else {
        params.rootId = replyUser.value.id
      }
    }

    const response = await addCommentUsingPost(params)

    if (response.data && response.data.code === 0) {
      // 评论成功，清空内容
      commentContent.value = ''
      message.success('评论成功')

      // 触发评论添加事件
      emit('comment-added')

      // 如果是回复评论，更新子评论列表
      if (replyUser.value) {
        // 找到根评论ID
        const rootId = params.rootId

        // 找到对应的根评论
        const rootComment = rootComments.value.find((item) => item.id === rootId)
        if (rootComment) {
          // 更新子评论计数
          if (rootComment.childCount !== undefined) {
            rootComment.childCount += 1
          } else {
            rootComment.childCount = 1
          }

          // 如果已经加载了子评论，重新加载
          if (rootComment.children && rootComment.children.length > 0) {
            await loadReplies(rootId as number)
          }
        }

        // 清除回复状态
        cancelReply()
      } else {
        // 刷新评论列表以显示新评论
        await loadRootComments()
      }
    } else {
      message.error(response.data?.message || '评论失败')
    }
  } catch (error) {
    message.error('评论失败')
    console.error(error)
  } finally {
    submitting.value = false
  }
}

// 回复评论
const handleReply = (comment: API.CommentVO, rootComment: API.CommentVO | null = null) => {
  replyUser.value = comment
  replyRootComment.value = rootComment
  // 滚动到评论输入框
  const inputEl = document.querySelector('.comment-input')
  if (inputEl) {
    inputEl.scrollIntoView({ behavior: 'smooth' })
  }
}

// 取消回复
const cancelReply = () => {
  replyUser.value = null
  replyRootComment.value = null
}

// 实现点赞功能（暂未实现后端接口）
const handleLike = async (comment: API.CommentVO) => {
  if (!currentUser.value) {
    message.warning('请先登录')
    return
  }

  message.info('点赞功能正在开发中')

  // 模拟点赞效果
  if (comment.hasLiked === false) {
    comment.hasLiked = true
    if (comment.likeCount !== undefined) {
      comment.likeCount += 1
    } else {
      comment.likeCount = 1
    }
  }
}

// 实现取消点赞功能（暂未实现后端接口）
const handleUnlike = async (comment: API.CommentVO) => {
  if (!currentUser.value) {
    message.warning('请先登录')
    return
  }

  message.info('取消点赞功能正在开发中')

  // 模拟取消点赞效果
  if (comment.hasLiked === true) {
    comment.hasLiked = false
    if (comment.likeCount !== undefined && comment.likeCount > 0) {
      comment.likeCount -= 1
    }
  }
}

// 删除评论
const handleDelete = async (comment: API.CommentVO) => {
  if (!canDelete(comment)) {
    message.warning('无权删除该评论')
    return
  }

  try {
    const response = await deleteCommentUsingPost({ id: comment.id })

    if (response.data && response.data.code === 0 && response.data.data) {
      // 如果是回复评论
      if (comment.parentId) {
        // 找到根评论
        const rootComment = rootComments.value.find((item) => item.id === comment.rootId)
        if (rootComment) {
          // 更新子评论计数
          if (rootComment.childCount !== undefined && rootComment.childCount > 0) {
            rootComment.childCount -= 1
          }
          // 从子评论列表中移除
          if (rootComment.children) {
            rootComment.children = rootComment.children.filter((item) => item.id !== comment.id)
          }
        }
      } else {
        // 一级评论，直接从列表移除
        rootComments.value = rootComments.value.filter((item) => item.id !== comment.id)
      }

      // 通知父组件执行删除函数
      emit('comment-deleted')

      message.success('删除成功')
    } else {
      message.error(response.data?.message || '删除失败')
    }
  } catch (error) {
    message.error('删除失败')
    console.error(error)
  }
}

// 判断用户是否可以删除评论
const canDelete = (comment: API.CommentVO) => {
  if (!currentUser.value) return false

  // 评论作者可以删除自己的评论
  if (comment.userId === currentUser.value.id) return true

  // 管理员可以删除任何评论
  if (currentUser.value.userRole === 'admin') return true

  return false
}

// 获取回复评论的显示内容
const getReplyContent = (reply: API.CommentVO) => {
  if (reply.replyUserName) {
    return `回复 @${reply.replyUserName}：${reply.content}`
  }
  return reply.content
}
</script>

<style scoped>
.comment-section {
  margin-top: 24px;
}

.comment-input {
  display: flex;
  flex-direction: column;
  margin-bottom: 24px;
  gap: 12px;
}

.comment-input .ant-avatar {
  margin-right: 12px;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 8px;
}

.comment-list {
  margin-top: 24px;
}

.reply-list {
  margin-top: 16px;
  padding-bottom: 5px;
  border-left: 1px solid #f0f0f0;
  background-color: #ffffff;
}

.reply-list.active {
  background-color: #f7f8fa;
}

.load-more {
  padding: 8px 0;
  text-align: center;
}

.isShow {
  display: flex;
  justify-content: center;
  margin: 10px 0 10px 0;
}

.clickable-text {
  cursor: pointer; /* 鼠标变手型 */
  color: #989a9c; /* 链接色 */
  transition: color 0.3s; /* 过渡效果 */
  margin-right: 2px;
}

.clickable-text:hover {
  color: #b66838; /* 悬停颜色 */
}
</style>
